<template>
  <div class="purchase-order-list-page">
    <!-- 主要内容区域 -->
    <div class="main-content">  

      <!-- 筛选器 -->
      <div class="filters">
        <el-form :model="queryParams" inline>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="选择状态" clearable style="width: 150px">
              <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="订单类型">
            <el-select v-model="queryParams.orderType" placeholder="选择类型" clearable style="width: 150px">
              <el-option
                v-for="type in orderTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="purchaseOrders"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="orderNumber" label="订单号" width="160" fixed="left">
            <template #default="{ row }">
              <el-link type="primary" @click="viewDetail(row.id)">
                {{ row.orderNumber }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="supplierName" label="供应商" width="200" />
          <el-table-column prop="orderType" label="订单类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getOrderTypeTagType(row.orderType)">
                {{ row.orderType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="订单金额" width="120" align="right">
            <template #default="{ row }">
              <span class="amount">¥{{ formatCurrency(row.totalAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="120" />
          <el-table-column prop="updateTime" label="更新时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click="viewDetail(row.id)">
                  详情
                </el-button>
                <el-button 
                  v-if="canEdit(row.status)" 
                  size="small" 
                  type="warning" 
                  @click="editOrder(row.id)"
                >
                  编辑
                </el-button>
                <el-dropdown @command="handleCommand" v-if="hasMoreActions(row)">
                  <el-button size="small" type="info">
                    更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        v-if="canSubmit(row.status)" 
                        :command="{ action: 'submit', id: row.id }"
                      >
                        提交审批
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="canWithdraw(row.status)" 
                        :command="{ action: 'withdraw', id: row.id }"
                      >
                        撤回
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="canApprove(row.status)" 
                        :command="{ action: 'approve', id: row.id }"
                      >
                        审批
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="canDelete(row.status)" 
                        :command="{ action: 'delete', id: row.id }"
                        divided
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageIndex"
          v-model:page-size="queryParams.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialog.visible"
      title="审批采购订单"
      width="500px"
      @close="closeApprovalDialog"
    >
      <el-form :model="approvalDialog.form" label-width="80px">
        <el-form-item label="审批决定">
          <el-radio-group v-model="approvalDialog.form.decision">
            <el-radio value="通过">同意</el-radio>
            <el-radio value="驳回">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalDialog.form.comments"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeApprovalDialog">取消</el-button>
          <el-button type="primary" @click="submitApproval" :loading="submitting">
            确认审批
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh, Download, ArrowDown } from '@element-plus/icons-vue'
import { usePurchaseOrderStore } from '@/stores/purchaseOrder'
import type { PurchaseOrderDto, PurchaseOrderQueryDto, ApprovalDecisionDto } from '@/types/console'

// 路由
const router = useRouter()

// 状态管理
const purchaseOrderStore = usePurchaseOrderStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const selectedOrders = ref<PurchaseOrderDto[]>([])
const dateRange = ref<[string, string]>(['', ''])

// 查询参数
const queryParams = ref<PurchaseOrderQueryDto>({
  pageIndex: 1,
  pageSize: 10,
  keyword: '',
  status: '',
  orderType: ''
})

// 审批对话框
const approvalDialog = reactive({
  visible: false,
  orderId: 0,
  form: {
            decision: '通过',
    comments: ''
  }
})

// 计算属性
const purchaseOrders = computed(() => purchaseOrderStore.purchaseOrders)
const pagination = computed(() => purchaseOrderStore.pagination)
const statistics = computed(() => purchaseOrderStore.statistics)

// 状态选项
const statusOptions = [
  { label: '草稿', value: '草稿' },
  { label: '待审批', value: '待审批' },
  { label: '审批中', value: '审批中' },
  { label: '已审批', value: '已审批' },
  { label: '已拒绝', value: '已拒绝' },
  { label: '已撤回', value: '已撤回' }
]

// 订单类型选项
const orderTypeOptions = [
  { label: '标准采购', value: '标准采购' },
  { label: '紧急采购', value: '紧急采购' },
  { label: '框架采购', value: '框架采购' },
  { label: '补充采购', value: '补充采购' }
]

// 生命周期
onMounted(() => {
  loadData()
})

// 监听查询参数变化
watch(
  () => [queryParams.value.status, queryParams.value.orderType],
  () => {
    handleSearch()
  }
)

// 方法
const loadData = async () => {
  loading.value = true
  try {
    await purchaseOrderStore.fetchPurchaseOrders(queryParams.value)
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  queryParams.value.pageIndex = 1
  loadData()
}

const handleDateRangeChange = (dates: [string, string] | null) => {
  if (dates) {
    queryParams.value.createStartTime = dates[0]
    queryParams.value.createEndTime = dates[1]
  } else {
    queryParams.value.createStartTime = undefined
    queryParams.value.createEndTime = undefined
  }
  handleSearch()
}

const resetFilters = () => {
  queryParams.value = {
    pageIndex: 1,
    pageSize: 20,
    keyword: '',
    status: '',
    orderType: ''
  }
  dateRange.value = ['', '']
  loadData()
}

const refreshData = () => {
  loadData()
}

const handleSizeChange = (size: number) => {
  queryParams.value.pageSize = size
  loadData()
}

const handleCurrentChange = (page: number) => {
  queryParams.value.pageIndex = page
  loadData()
}

const handleSelectionChange = (selection: PurchaseOrderDto[]) => {
  selectedOrders.value = selection
}

// 创建订单
const createOrder = () => {
  // 在新的嵌套路由结构下，这些功能由父组件处理
  ElMessage.info('请使用顶部的新增按钮创建采购订单')
}

// 查看详情
const viewDetail = (id: number) => {
  router.push(`/main/procurement/purchase-order/${id}`)
}

// 编辑订单
const editOrder = (id: number) => {
  router.push(`/main/procurement/purchase-order/${id}/edit`)
}

// 导出数据
const exportData = async () => {
  try {
    const extendedQuery = {
      ...queryParams.value,
      includeApprovalFlow: true
    }
    await purchaseOrderStore.exportPurchaseOrders(extendedQuery)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 处理命令
const handleCommand = (command: { action: string; id: number }) => {
  switch (command.action) {
    case 'submit':
      submitForApproval(command.id)
      break
    case 'withdraw':
      withdrawOrder(command.id)
      break
    case 'approve':
      showApprovalDialog(command.id)
      break
    case 'delete':
      deleteOrder(command.id)
      break
  }
}

// 提交审批
const submitForApproval = async (id: number) => {
  try {
    await ElMessageBox.confirm('确认提交该采购订单进行审批？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await purchaseOrderStore.submitForApproval(id)
    ElMessage.success('提交成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('提交失败')
    }
  }
}

// 撤回订单
const withdrawOrder = async (id: number) => {
  try {
    await ElMessageBox.confirm('确认撤回该采购订单？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await purchaseOrderStore.withdrawOrder(id)
    ElMessage.success('撤回成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('撤回失败')
    }
  }
}

// 显示审批对话框
const showApprovalDialog = (id: number) => {
  approvalDialog.visible = true
  approvalDialog.orderId = id
  approvalDialog.form = {
    decision: '通过',
    comments: ''
  }
}

// 关闭审批对话框
const closeApprovalDialog = () => {
  approvalDialog.visible = false
  approvalDialog.orderId = 0
  approvalDialog.form = {
    decision: '通过',
    comments: ''
  }
}

// 提交审批
const submitApproval = async () => {
  submitting.value = true
  try {
    const decision: ApprovalDecisionDto = {
      decision: approvalDialog.form.decision,
      comments: approvalDialog.form.comments,
      attachmentUrls: []
    }
    
    await purchaseOrderStore.approveOrder(approvalDialog.orderId, decision)
    ElMessage.success('审批成功')
    closeApprovalDialog()
    loadData()
  } catch (error) {
    ElMessage.error('审批失败')
  } finally {
    submitting.value = false
  }
}

// 删除订单
const deleteOrder = async (id: number) => {
  try {
    await ElMessageBox.confirm('确认删除该采购订单？删除后不可恢复！', '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    const result = await purchaseOrderStore.deletePurchaseOrder(id)
    if (result.code === 200) {
      ElMessage.success('删除成功')
      // 删除成功后不需要重新加载数据，store已经处理了本地状态更新
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 工具方法
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '草稿': 'info',
    '待审批': 'warning',
    '审批中': 'primary',
    '已审批': 'success',
    '已拒绝': 'danger',
    '已撤回': 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  return status
}

const getOrderTypeTagType = (orderType: string) => {
  const typeMap: Record<string, string> = {
    '标准采购': '',
    '紧急采购': 'danger',
    '框架采购': 'success',
    '补充采购': 'warning'
  }
  return typeMap[orderType] || ''
}

// 权限控制方法
const canEdit = (status: string) => {
  return ['草稿', '已拒绝'].includes(status)
}

const canSubmit = (status: string) => {
  return status === '草稿'
}

const canWithdraw = (status: string) => {
  return status === '待审批'
}

const canApprove = (status: string) => {
  return ['待审批', '审批中'].includes(status)
}

const canDelete = (status: string) => {
  return ['草稿', '已拒绝'].includes(status)
}

const hasMoreActions = (row: PurchaseOrderDto) => {
  return canSubmit(row.status) || canWithdraw(row.status) || canApprove(row.status) || canDelete(row.status)
}

// 供父组件调用的搜索方法
const performSearch = (keyword: string) => {
  queryParams.value.keyword = keyword
  handleSearch()
}

// 暴露方法给父组件
defineExpose({
  performSearch
})
</script>

<style scoped>
.purchase-order-list-page {
  background: white;
}



.main-content {
  padding: 20px;
}

.toolbar {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 0.5rem;
}

.toolbar-right {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.filters {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.amount {
  font-weight: 600;
  color: #67c23a;
}

.action-buttons {
  display: flex;
  gap: 0.25rem;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px;
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-content {
    padding: 1rem;
    flex-direction: column;
    gap: 1rem;
  }

  .main-content {
    padding: 1rem;
  }

  .toolbar {
    flex-direction: column;
    gap: 1rem;
  }

  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: center;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style> 